﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.IO;
using System.Linq;
using NDBGen.Plugins;
using NDBGen.Plugins.DataAccess;

namespace NDBGen
{
    public class PluginLibraries
    {
        public static void Init()
        {
            var assembly = typeof(PluginLibraries).Assembly;
            var currentDir = new FileInfo(assembly.Location).Directory;
            IEnumerable<String> pluginDirs = new String[0];
            
            if (currentDir.Name == "net40" &&
                currentDir.Parent.Name == "lib" &&
                currentDir.Parent.Parent.Parent.Name == "packages")
            {
                pluginDirs =
                    from plugin in currentDir.Parent.Parent.Parent.GetDirectories("NDBGen.Plugins.*")
                    select Path.Combine(plugin.FullName, @"lib\net40");
            }

            var catalog = new AggregateCatalog(pluginDirs.Select(d => new DirectoryCatalog(d)));
            catalog.Catalogs.Add(new AssemblyCatalog(assembly));

            PluginLibraries.Catalog = catalog;
        }

        public static ComposablePartCatalog Catalog { get; private set; }

        internal PluginLibraries()
        {
            this.DataAccessCodeGenerators = new ExportLibrary<IDataAccessCodeFileGenerator, INamedPluginMetadata>(PluginLibraries.Catalog);
            this.DataAccessProjectFileManagers = new ExportLibrary<IProjectFileManager, INamedPluginMetadata>(PluginLibraries.Catalog);
            this.DatabaseScriptGenerators = new ExportLibrary<IDatabaseScriptFileGenerator, INamedPluginMetadata>(PluginLibraries.Catalog);
        }

        internal ExportLibrary<IDataAccessCodeFileGenerator, INamedPluginMetadata> DataAccessCodeGenerators { get; set; }
        internal ExportLibrary<IProjectFileManager, INamedPluginMetadata> DataAccessProjectFileManagers { get; set; }
        internal ExportLibrary<IDatabaseScriptFileGenerator, INamedPluginMetadata> DatabaseScriptGenerators { get; set; }
    }
}